<div class="layui-card-header layui-card">
    <span class="layui-breadcrumb" lay-filter="breadcrumb">
        <a lay-href="">首页</a>
        <a><cite>支付配置</cite></a>
        <a><cite>接口类型</cite></a>
        <a><cite>账号模板</cite></a>
    </span>
</div>
<div class="layui-fluid">
    <div class="layui-card">
        <div class="layui-tab layui-tab-brief">
            <ul class="layui-tab-title">
                <li class="layui-this">账号模板列表</li>
            </ul>
            <div class="layui-tab-content">
                <div class="layui-row">
                    <div class="layuiAdmin-btns" style="margin-bottom: 10px;">
                        <a class="layui-btn create" data-events="create"><i class="layui-icon layui-icon-add-1"></i>新增账号模板</a>
                        <a class="layui-btn layui-btn-danger relationDelete"><i class="layui-icon layui-icon-delete"></i>彻底删除</a>
                    </div>
                </div>
                <table class="layui-hide center" id="cList" lay-filter='cList'></table>
            </div>
        </div>
    </div>
</div>
<script>
    layui.use(['table','util', 'form'], function(){
        var table = layui.table
        ,$ = layui.$
        ,form = layui.form
        ,element = layui.element
        ,view = layui.view
        ,admin = layui.admin;
        var ifTypeCode = layui.router().search.ifTypeCode;

        element.render('breadcrumb', 'breadcrumb');//渲染导航信息

        //标题内容模板
        var tplTitle = function(d){
            var mchHtml = "";
            if (ifTypeCode == "alizftpay") {
                mchHtml = "<a class='layui-btn layui-btn-xs layui-btn-normal' lay-event='subMchList'><i class='layui-icon layui-icon-list'></i>二级商户</a>";
            }
            return "<a class='layui-btn layui-btn-xs layui-btn-sm' lay-event='edit'><i class='layui-icon layui-icon-edit'></i>编辑</a>" + mchHtml;
            // return '<a class="layui-btn layui-btn-sm" lay-href="config/pay_interface_type/template/update/tid='+d.id+'/ifTypeCode='+ d.ifTypeCode +'">编辑</a>';
        };

        var tplStatus = function(d){
            var checkedHtml = " recordId='"+d.id+"' ";
            if(d.status == 1) {
                checkedHtml += " checked";
            }
            return '<input type="checkbox" lay-filter="statusSwitch" lay-skin="switch" '+checkedHtml+' lay-text="启用|停用">';
        };
        table.render({
            elem: '#cList'
            ,url: layui.setter.baseUrl + '/config/pay_interface_type/template/list'
            ,where : {access_token: layui.data(layui.setter.tableName).access_token, ifTypeCode : ifTypeCode, 'ps[belongInfoTypeIn]': "[1,4]" }
            ,id: 'tableReload'
            ,cols: [[
                {type: 'checkbox', fixed: 'left'}
                ,{field:'id', title: 'ID'}
                ,{field:'passageMchIdTemplate', title: '通道商户ID'}
                ,{title: '所属平台', templet: "<div>{{d.belongInfoType == 1 ? '运营平台': '-'}}</div>"}
                ,{field:'ifTypeCode', title: '接口类型代码'}
                ,{field:'templateName',  title: '接口类型名称'}
                ,{field:'status', title: '状态',templet: tplStatus }
                ,{field: 'createTime', title: '创建时间', templet: '<div>{{ layui.util.toDateString(d.createTime, "yyyy-MM-dd HH:mm:ss") }}</div>'}
                ,{width: 200, title: '操作', fixed: 'right', templet: tplTitle }
            ]]
            ,page: true
            ,skin: 'line'
        });

        //监听工具条
        table.on('tool(cList)', function(obj){
          var data = obj.data;
          if(obj.event === 'syncAccountParam'){
        	  layer.confirm('确定将模板配置信息同步到设置该支付类型的所有通道子账户？',function(index){
        		  
        		  admin.req({
			            type: 'post',
			            url: layui.setter.baseUrl + '/config/pay_interface_type/template/syncAccountParam',
			            data: {id: data.id},
			            error: function(err){layer.alert(err.msg,{title:"请求失败"})},
			            success: function(res){
			                if(res.code == 0){
			                    layer.alert('共更新'+res.data+'条记录', {title: '同步成功'},function(index){
			                    	layer.close(index);
			                    });
			                }
			            }
			        });
        	  });
          }else if(obj.event === 'edit'){
              view.xxpayPopup("更新账户模板", "config/pay_interface_type/template/update", {tid: data.id, ifTypeCode: ifTypeCode});
          }else if (obj.event == 'subMchList') {
              location.href = layui.setter.baseLocal + "config/pay_interface_type/template/sub_mch_list/list/id="+ data.id+"/ifTypeCode="+ifTypeCode;
          }
        });


        form.on('switch(statusSwitch)', function(data){

            var updateRecordId = $(data.elem).attr('recordId');
            var updateState = data.elem.checked ? "1" : "0";
            var loadingIndex = layer.load();
            admin.req({
                type: "POST",
                url: layui.setter.baseUrl + '/config/pay_interface_type/template/update',
                data: {id: updateRecordId, status: updateState},
                success: function(res){
                    if(res.code == 0) {
                        table.reload('tableReload');
                    }
                },
                complete:function(){
                    layer.close(loadingIndex);
                }
            });
        });

        // 事件处理
        var events = {
            create: function(othis, type){
                view.xxpayPopup("新增账号模板", "config/pay_interface_type/template/create", {ifTypeCode: ifTypeCode});
            }
        };

        $('.layuiAdmin-btns .layui-btn').on('click', function(){
            var othis = $(this)
                ,thisEvent = othis.data('events')
                ,type = othis.data('type');
            events[thisEvent] && events[thisEvent].call(this, othis, type);
        });

        $('.layuiAdmin-btns .relationDelete').on('click', function(){
            var checkedData = table.checkStatus("tableReload").data; //获得选中的数据
            if (checkedData.length === 0) return layer.msg('请选择数据');
            var delIds = [];
            $.each(checkedData, function () {
                delIds.push(this.id);
            });

            //弹层
            var relationDeleteHtml = `
                <div style="color:red; margin:20px; padding-left:50px" >
                    <label class="layui-inline"> 此操作将删除选中数据及所有关联数据！是否继续删除？</label><br/><br/>
                    <label class="layui-inline"> 关联表：[支付子账号表];[账号模板表];</label>
                </div>
                <form class="layui-form center">
                    <div class="layui-form-item" style="margin-top:20px">
                        <label class="layui-form-label" style="width:130px;">是否删除红包记录：</label>
                        <div class="layui-input-inline" style="width: 312px;">
                            <input type="radio" name="isDeleteAlipayCash" value="1" title="是">
                            <input type="radio" name="isDeleteAlipayCash" value="0" title="否" checked>
                        </div>
                    </div>
                    <div class="layui-form-item" style="margin-top:30px">
                        <div class="layui-input-block" style="margin-left: 180px;">
                            <button type="button" class="layui-btn layui-btn-danger relationDeleteBtn">确认删除</button>
                            <button type="button" class="layui-btn layui-btn-normal" onclick="layer.closeAll();">取消</button>
                        </div>
                    </div>
                </form>
            `;
            //打开弹层
            var thisLayerId = layer.open({type: 1, area: ['520px', 'auto'], title: '提示', content: relationDeleteHtml});
            form.render();
            $(".relationDeleteBtn").click(function () {

                var layerMsgId = layer.msg('正在执行删除任务... ', {time: 0, shade: 0.3});
                admin.req({
                    type: 'get',
                    url: layui.setter.baseUrl + '/config/pay_interface_type/template/relationDelete',
                    data: {ids: JSON.stringify(delIds), isDeleteAlipayCash : $('input[name="isDeleteAlipayCash"]:checked').val()},
                    error: function (err) {
                        layer.close(layerMsgId);
                        layer.alert(err);
                    },
                    success: function (res) {
                        layer.close(layerMsgId);
                        if (res.code == '0') { //成功创建任务
                            layer.close(thisLayerId);
                            table.reload('tableReload');  //刷新页面
                            layer.alert("操作成功, 共删除了 "+res.data+" 条关联数据！");
                        }
                    }
                });
            });
        });
        
        // 渲染表单
        form.render();

    });
    
</script>
